package com.dai.zhenfujin.addresslist.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.dai.zhenfujin.BaseAdapter.BaseViewHolder;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.Constants.EventConstants;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.adapter.AttentionDetailAdapter;
import com.dai.zhenfujin.base.BaseFragment;
import com.dai.zhenfujin.bean.FollowBean;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.view.WrapContentLinearLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 通讯录中的关注列表
 */
public class AttentionViewPagerFragment extends BaseFragment {

    private RecyclerView rlAttention;
    private ImageView iv_no_msg;
    public static List<FollowBean.FollowListBean> followList = new ArrayList<>();
    private AttentionDetailAdapter attentionDetailAdapter;
    private int page = 1;
    private int number = 10;
    private SmartRefreshLayout refreshLayout;
    private EditText query;
    protected ImageButton clearSearch;
    protected InputMethodManager inputMethodManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @Override
    public View initView() {
        View view = View.inflate(mContext, com.dai.zhenfujin.R.layout.fragment_attention, null);
        rlAttention = view.findViewById(com.dai.zhenfujin.R.id.rl_attention);
        iv_no_msg = view.findViewById(com.dai.zhenfujin.R.id.iv_no_msg);
        query = view.findViewById(R.id.query);
        clearSearch = view.findViewById(com.hyphenate.easeui.R.id.search_clear);
        refreshLayout = view.findViewById(com.dai.zhenfujin.R.id.refreshLayout);
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        rlAttention.setLayoutManager(new WrapContentLinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        attentionDetailAdapter = new AttentionDetailAdapter(mContext, followList, new TypeItemListener());
        rlAttention.setAdapter(attentionDetailAdapter);
        onRefresh();
        initRefresh();
        initQuery();
       // getFollowList();
    }

    private void initQuery() {
        query.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索的时候隐藏软键盘
                  //  hideKeyboard(EditText);
                    // 在这里写搜索的操作,一般都是网络请求数据
                    page = 1;
                    getFollowList(true,v.getText().toString().trim());
                    return true;
                }

                return false;
            }
        });

        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);
                    page = 1;
                    getFollowList(true,s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });
    }

    private void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void initRefresh() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
                        getFollowList(true,"");
                        refreshLayout.finishRefresh();
                        refreshLayout.resetNoMoreData();
                    }
                },1500);
            }
        });

        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getFollowList(false,"");
            }
        });
    }

    private void onRefresh() {
        page = 1;
        getFollowList(true,"");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event != null && event.getMessageKey() != null) {
            if (event.getMessageKey().equals(EventConstants.UPDATA_FOLLOW_LIST)) {
                page = 1;
                getFollowList(true,"");
            }
        }
    }


    private void getFollowList(boolean isRefresh,String word) {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("page", page + "");
        params2.put("number", number + "");
        if (!TextUtils.isEmpty(word))
        params2.put("word", word);
        params.put("req_bd", params2);
        HttpClient.post(mContext, Constants.FOLLOWLIST, params, new CallBack<FollowBean>() {
            @Override
            public void onSuccess(FollowBean resultBean) {
                if (isRefresh) {
                    followList.clear();
                    if (resultBean.followList.size() == 0){
                        followList.addAll(resultBean.followList);
                        attentionDetailAdapter.notifyDataSetChanged();
                        //iv_no_msg.setVisibility(View.VISIBLE);
                        return;
                    }
                    page = 2;
                } else {
                    page++;
                    refreshLayout.finishLoadmore();
                }

                if (resultBean.followList.size() > 0) {
                   // attentionDetailAdapter.notifyDataSetChanged();
                  //  attentionDetailAdapter.notifyItemRangeRemoved(0, followList.size());
                    followList.addAll(resultBean.followList);
                    attentionDetailAdapter.notifyItemRangeChanged(0,resultBean.followList.size());
                    if (page==2)
                        iv_no_msg.setVisibility(View.GONE);
                }else {
                    //  UIUtils.showToastSafe("暂无数据");
                    refreshLayout.finishLoadmoreWithNoMoreData();//将不会再次触发加载更多事件
                  //  if (page==2)
                        //iv_no_msg.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    class TypeItemListener implements BaseViewHolder.onItemCommonClickListener {

        @Override
        public void onItemClickListener(int position) {

        }

        @Override
        public void onItemLongClickListener(int position) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
